package com.comp6521.project01;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class OutputBuffer extends Buffer {

	private BufferedWriter bufferWriter = null;
	
	public OutputBuffer(int bufferSize, String filename) {
		super(bufferSize, filename);
		try {
			bufferWriter = new BufferedWriter(new FileWriter(getFilename()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// write to file
	public void flush() {
		
		int size = data.size();
		for(int i = 0; i <size ; ++i)
		{
			String temp = Integer.toString(data.poll());
			temp += "\r\n";
			try {
				bufferWriter.write(temp);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	void add(int val) {
		if (data.size() >= getBufferSize())
			flush();
		data.add(val);
	}
	
	void close() {
		try {
			flush();
			bufferWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
